package com.yao2san.simcasserver.config;

import com.yao2san.simcasserver.filter.AuthenticationFilter;
import com.yao2san.simcasserver.processor.AbstractDatabaseAuthenticationProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

@Configuration
public class SimCasServerAutoConfiguration {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Bean
    public ProcessorConfiguration processorConfiguration() {
        ProcessorConfiguration processorConfiguration = new ProcessorConfiguration();
        return processorConfiguration;
    }

    @Bean
    //@ConditionalOnProperty("sim.cas.processor")
    public FilterRegistrationBean<AuthenticationFilter> filterRegistrationBean(ProcessorConfiguration processorConfiguration) {
        Class<? extends AbstractDatabaseAuthenticationProcessor> processClass = processorConfiguration.getProcessClass();

        AbstractDatabaseAuthenticationProcessor abstractDatabaseAuthenticationProcessor = null;
        try {
            abstractDatabaseAuthenticationProcessor = processClass.newInstance();
            abstractDatabaseAuthenticationProcessor.setFiledMapping(processorConfiguration.getFiledMapping());
            abstractDatabaseAuthenticationProcessor.setProcessorConfiguration(processorConfiguration);
            abstractDatabaseAuthenticationProcessor.setJdbcTemplate(jdbcTemplate);
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        FilterRegistrationBean<AuthenticationFilter> bean = new FilterRegistrationBean<>();
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(abstractDatabaseAuthenticationProcessor);

        bean.setFilter(authenticationFilter);
        bean.setOrder(1);
        bean.setName("authenticationFilter");
        return bean;
    }
}
